package com.cycplus.test

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.os.Bundle
import android.view.View
import android.view.ViewPropertyAnimator
import android.view.animation.AccelerateDecelerateInterpolator
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.transition.TransitionManager
import com.cycplus.test.base.BaseBindingActivity
import com.cycplus.test.databinding.ActivityVideoScrollBinding
import com.cycplus.test.ui.GridLastRowMarginDecoration
import com.cycplus.test.ui.HighLightMomentAdapter
import com.cycplus.test.utils.ScreenUtil
import com.google.android.material.appbar.AppBarLayout
import com.gyf.immersionbar.ImmersionBar

class VideoScrollActivity : BaseBindingActivity<ActivityVideoScrollBinding>() {

    private var lastOffset = 0
    private var lastDirection = 0
    private var isBottomMenuVisible = true
    private var bottomMenuAnimator: ViewPropertyAnimator? = null
    private var isTopMenuVisible = true
    private var topMenuAnimator: ViewPropertyAnimator? = null
    private var clZoneInitialHeight: Int = 0

    override fun initImmersionBar() {
        ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(R.color.color_0f0f0f).navigationBarColor(R.color.color_0f0f0f)
            .autoDarkModeEnable(true).init()
    }

    override fun initView(rootView: View, savedInstanceState: Bundle?) {
        mBinding.rvHighLight.layoutManager = GridLayoutManager(this, 2)
        mBinding.rvHighLight.addItemDecoration(GridLastRowMarginDecoration(2, ScreenUtil.dp2px(this, 30f)))
        mBinding.rvHighLight.adapter = HighLightMomentAdapter(
            arrayListOf(
                "1",
                "2",
                "3",
                "4",
                "5",
                "6",
                "7",
                "8",
                "9",
                "10",
                "11",
                "12",
                "13",
                "14"
            )
        )

        mBinding.apply {
            appBarLayout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { _, offset ->
                if (offset == lastOffset) {
                    return@OnOffsetChangedListener
                }
                val direction = if (offset < lastOffset) { //向上滑（收起）
                    -1
                } else { //向下滑（展开）
                    1
                }
                if (direction != lastDirection) {
                    lastDirection = direction
                    if (direction == -1) {
                        hideViews()
                    } else {
                        showViews()
                    }
                }
                lastOffset = offset
            })

            rvHighLight.addOnScrollListener(object : RecyclerView.OnScrollListener() {
                override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                    if (dy > 10) {
                        hideViews()
                    } else if (dy < -10) {
                        showViews()
                    }
                }
            })
        }
    }

    private fun hideViews() {
        if (clZoneInitialHeight == 0) {
            clZoneInitialHeight = mBinding.clVideoZone.height
        }
        if (!isBottomMenuVisible) {
            return
        }
        //1 隐藏底部菜单
        bottomMenuAnimator?.cancel()
        bottomMenuAnimator = mBinding.bottomMenu.animate()
            .translationY(mBinding.bottomMenu.height.toFloat())
            .alpha(0f)
            .setDuration(200)
            .withEndAction {
                isBottomMenuVisible = false
            }

        //2 隐藏顶部菜单
        val topMenuHeight = mBinding.rlTopMenu.height

        val animator = ValueAnimator.ofFloat(0f, topMenuHeight.toFloat())
        animator.duration = 200
        animator.interpolator = AccelerateDecelerateInterpolator()
        animator.addUpdateListener { animation ->
            val animatedValue = animation.animatedValue as Float

            mBinding.rlTopMenu.translationY = -animatedValue
            mBinding.rlTopMenu.alpha = 1f - (animatedValue / topMenuHeight)
        }
        animator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                val constraintLayout = mBinding.root
                val constraintSet = ConstraintSet()
                constraintSet.clone(constraintLayout)
                constraintSet.clear(R.id.clVideoZone, ConstraintSet.TOP)
                constraintSet.connect(
                    R.id.clVideoZone,
                    ConstraintSet.TOP,
                    ConstraintSet.PARENT_ID,
                    ConstraintSet.TOP
                )
                mBinding.clVideoZone.updateLayoutParams<ConstraintLayout.LayoutParams> {
                    height += topMenuHeight
                }
                TransitionManager.beginDelayedTransition(constraintLayout)
                constraintSet.applyTo(constraintLayout)

            }
        })
        animator.start()
    }

    private fun showViews() {
        if (isBottomMenuVisible) {
            return
        }
        //1 显示底部菜单
        bottomMenuAnimator?.cancel()
        bottomMenuAnimator = mBinding.bottomMenu.animate()
            .translationY(0f)
            .alpha(1f)
            .setDuration(200)
            .withEndAction {
                isBottomMenuVisible = true
            }
        topMenuAnimator?.cancel()
        topMenuAnimator = mBinding.rlTopMenu.animate()
            .translationY(0f)
            .alpha(1f)
            .setDuration(200)
            .withEndAction {
                isTopMenuVisible = true
            }

        //2 显示顶部菜单
        val topMenuHeight = mBinding.rlTopMenu.height
        val animator = ValueAnimator.ofFloat(0f, topMenuHeight.toFloat())
        animator.duration = 200
        animator.interpolator = AccelerateDecelerateInterpolator()
        animator.addUpdateListener { animation ->
            val animatedValue = animation.animatedValue as Float

            mBinding.rlTopMenu.translationY = topMenuHeight - animatedValue
            mBinding.rlTopMenu.alpha = animatedValue / topMenuHeight
        }
        animator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                val constraintLayout = mBinding.root
                val constraintSet = ConstraintSet()
                constraintSet.clone(constraintLayout)
                constraintSet.clear(R.id.clVideoZone, ConstraintSet.TOP)
                constraintSet.connect(
                    R.id.clVideoZone,
                    ConstraintSet.TOP,
                    R.id.rlTopMenu,
                    ConstraintSet.BOTTOM
                )
                mBinding.clVideoZone.updateLayoutParams<ConstraintLayout.LayoutParams> {
                    height -= topMenuHeight
                }
                TransitionManager.beginDelayedTransition(constraintLayout)
                constraintSet.applyTo(constraintLayout)

            }
        })
        animator.start()
    }

}


